package cn.kgc.utils;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * @author wangyue
 * @version 1.0
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class SmsSender {
    @Resource
    private SmsProperties smsProperties;

    /**
     * 模拟发送短信
     * @param phone 手机号
     * @param code 短信验证码
     * @return 是否成功
     */
    public boolean mockSend(String phone,String code){
        //产生一位随机数
        int num = Integer.parseInt(RandomUtil.randomNumbers(1));
        if(num<=7){
            //第三方发送短信成功  0 1 2 4 5 6 7
            log.info("第三方短信发送成功");
            return true;
        }else{
            //第三方发送短信异常
            log.error("第三方短信发送失败(返回异常)");
            throw new RuntimeException("第三方短信发送异常");
        }
    }


    public Client createClient() throws Exception {
        Config config =new Config()
                .setAccessKeyId(smsProperties.getKeyId())
                .setAccessKeySecret(smsProperties.getKeySecret());
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public void sendMsg(String phoneNumber,String code) throws Exception{
        Client client= createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName(smsProperties.getSignName())
                .setTemplateCode(smsProperties.getTemplateCode())
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        client.sendSmsWithOptions(sendSmsRequest, runtime);
    }


}
